package vip.xiaonuo.smzq.modular.lifecycle.service.module.impl;

import ch.qos.logback.core.spi.LifeCycle;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.smzq.modular.drkqs.service.IKclZbService;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.Zlxqcx;
import vip.xiaonuo.smzq.modular.kcl.service.IZbService;
import vip.xiaonuo.smzq.modular.lifecycle.base.QueryLifeCycleBase;
import vip.xiaonuo.smzq.modular.lifecycle.constant.LifeCycleConstant;
import vip.xiaonuo.smzq.modular.lifecycle.constant.WebResultStatusConstant;
import vip.xiaonuo.smzq.modular.lifecycle.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.funcEnum.FuncEnum;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.module.CommonMapper;
import vip.xiaonuo.smzq.modular.lifecycle.mapper.module.LifeCycleMapper;
import vip.xiaonuo.smzq.modular.lifecycle.po.*;
import vip.xiaonuo.smzq.modular.lifecycle.po.datamanager.CheckNodeDatePO;
import vip.xiaonuo.smzq.modular.lifecycle.po.datamanager.SaveLCNodePO;
import vip.xiaonuo.smzq.modular.lifecycle.result.WebResult;
import vip.xiaonuo.smzq.modular.lifecycle.service.ExtCallService;
import vip.xiaonuo.smzq.modular.lifecycle.service.entity.*;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleDataManagerService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleHanderDataService;
import vip.xiaonuo.smzq.modular.lifecycle.service.module.LifeCycleService;
import vip.xiaonuo.smzq.modular.lifecycle.util.CoordinateTranUtil;
import vip.xiaonuo.smzq.modular.lifecycle.util.HutoolTreeExtend;
import vip.xiaonuo.smzq.modular.lifecycle.vo.*;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.AdJoinPedNodeVO;
import vip.xiaonuo.smzq.modular.lifecycle.vo.datamanager.LifeCyclePedigeeNodeVO;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <ul>
 * <li>name:  LifeCycleHanderDataServiceImpl</li>
 * <li>author name: GEOSCENE_YUYANFEI</li>
 * <li>create time: 2024-03-22 09:53:25</li>
 * </ul>
 */
@Slf4j
@Service
public class LifeCycleHanderDataServiceImpl implements LifeCycleHanderDataService {
    @Autowired
    KclCb01ZhMapper kclCb01ZhMapper;

    @Autowired
    KclZyclMapper kclZyclMapper;

    @Autowired
    KclZbMapper kclZbMapper;

    @Autowired
    LifeCycleMineStoreMapper lifeCycleMineStoreMapper;

    @Autowired
    LifeCycleMapper lifeCycleMapper;

    @Autowired
    LifeCycleMineStoreService lifeCycleMineStoreService;

    @Autowired
    LifeCycleService lifeCycleService;

    @Autowired
    LifeCycleMineralMeaService lifeCycleMineralMeaService;

    @Autowired
    LifeCyclePedigeeService lifeCyclePedigeeService;

    @Autowired
    KclKsService kclKsService;

    @Autowired
    LifeCycleDataManagerService lifeCycleDataManagerService;
    @Autowired
    KclCb06KcMapper kclCb06KcMapper;


    @Override
    @Transactional
    public boolean saveLifeCycleData(List<Zlxqcx> zlxqcxList) {
        boolean result = true;
        if(CollUtil.isNotEmpty(zlxqcxList)){
            for (Zlxqcx zlxqcx:zlxqcxList) {
                LifeCycleMineStore lifeCycleMineStore = new LifeCycleMineStore();
                lifeCycleMineStore.setApproveStatus(1);
                saveLifeCycleDataSingle(zlxqcx,lifeCycleMineStore);
            }

        }

        return result;
    }
//    保存生命周期数据
    private boolean saveLifeCycleDataSingle(Zlxqcx zlxqcx,LifeCycleMineStore lifeCycleMineStore){
        boolean result = true;
        lifeCycleMineStore = getMineStoreByZlxqcx(zlxqcx,lifeCycleMineStore);
        result =lifeCycleMineStoreService.save(lifeCycleMineStore);
//                  保存矿石类型储量值
        result = saveCycleLifeMineralMea(lifeCycleMineStore);
//        处理族谱数据
        result = handerPed(lifeCycleMineStore);

        return result;
    }

    /**
     * 得到矿山的最后一个族谱节点
     * @param mineralCode 矿区编号
     * @param regClassCode 登记分类编号
     * @return
     */
    private LifeCyclePedigee getMineLastPed(String mineralCode,Integer regClassCode){
        List<LifeCyclePedigee> lifeCyclePedigees = lifeCyclePedigeeService.lambdaQuery()
                .eq(LifeCyclePedigee::getMineralCode,mineralCode)
                .eq(LifeCyclePedigee::getRegClassCode,regClassCode).list();
        if(CollUtil.size(lifeCyclePedigees)!=0){
            lifeCyclePedigees =CollUtil.sortByProperty(lifeCyclePedigees,"id");

            return CollUtil.getLast(lifeCyclePedigees);
        }
        return null;
    }

    /**
     * 得到族谱对象
     * @param lifeCycleMineStore
     * @param xlInd
     * @param parentId
     * @return
     */
    private LifeCyclePedigee getPedObj(LifeCycleMineStore lifeCycleMineStore,Integer xlInd,String parentId){
        LifeCyclePedigee result = BeanUtil.copyProperties(lifeCycleMineStore,LifeCyclePedigee.class);
        String pedId = lifeCycleDataManagerService.getPedId(lifeCycleMineStore.getMineralCode(),lifeCycleMineStore.getRegClassCode(),lifeCycleMineStore.getStoreDate(),xlInd);
        result.setMineStoreId(lifeCycleMineStore.getId());
        result.setParentId(parentId);
        result.setId(pedId);
        result.setMainMine(true);
        return result;

    }

    /**
     * 操作族谱节点
     * @param lifeCycleMineStore 生命周期bean
     */
    private boolean handerPed(LifeCycleMineStore lifeCycleMineStore){
        boolean result = true;
//        如果是生成族谱的条件
        if(CollUtil.contains(LifeCycleConstant.crePedNodTypes, lifeCycleMineStore.getReportName())){
            LifeCyclePedigee lastPed = getMineLastPed(lifeCycleMineStore.getMineralCode(), lifeCycleMineStore.getRegClassCode());
//            族谱id
            if(StrUtil.equals("压覆报告", lifeCycleMineStore.getReportName())){
                if(ObjectUtil.isNotEmpty(lastPed)){
                    result = lifeCyclePedigeeService.saveBatch(CollUtil.newArrayList(getPedObj(lifeCycleMineStore,1,lastPed.getParentId()),getPedObj(lifeCycleMineStore,2,lastPed.getParentId())),2);
                }
            }else{
                result = lifeCyclePedigeeService.save(getPedObj(lifeCycleMineStore,null,lastPed.getId()));
            }
        }

        return result;

    }

    /*private  MPJLambdaQueryWrapper<LifeCycleMineStore> getQueryLifeBaseWrapper(QueryLifeCycleBase queryLifeCycleBase){
        return new MPJLambdaQueryWrapper<LifeCycleMineStore>()
                .eq(LifeCycleMineStore::getRegClassCode,queryLifeCycleBase.getRegClassCode())
                .eq(LifeCycleMineStore::getYear, queryLifeCycleBase.getYear())
                .eq(LifeCycleMineStore::getMineralCode, queryLifeCycleBase.getMineralCode());
    }*/

    @Override
    @Transactional
    public boolean savePedigeeWhenApproveed(SavePedigeePO savePedigeePO) {
        boolean result = true;
        KclKs kclKs = new KclKs();
        kclKs.setXkzh(savePedigeePO.getParentId());
//        kclKs.setNd(savePedigeePO.getYear());

        List<KclKs> kclKsList = kclKsService.queryKclKsList(kclKs);


        if(CollUtil.isNotEmpty(kclKsList)){
            KclKs kclKs1 = CollUtil.getFirst(kclKsList);
            savePedigeePO.setRegClassCode(kclKs1.getDjflbh());
            savePedigeePO.setMineralCode(kclKs1.getKqbh());
            savePedigeePO.setYear(kclKs1.getNd());
            Zlxqcx zlxqcx = new Zlxqcx();
            zlxqcx.setDjflbh(savePedigeePO.getRegClassCode());
            zlxqcx.setNd(savePedigeePO.getYear());
            zlxqcx.setKqbh(savePedigeePO.getMineralCode());
            zlxqcx.setZlsj(savePedigeePO.getStoreDate());
            zlxqcx.setKyqklx(savePedigeePO.getExportType());
            zlxqcx.setZlxz(savePedigeePO.getReportCode());
            zlxqcx.setNd(savePedigeePO.getYear());
            zlxqcx.setGuanlianId(savePedigeePO.getFileId());
//            LifeCycleMineStore lifeCycleMineStore = new LifeCycleMineStore();
//            lifeCycleMineStore.
            /*List<LifeCycleMineStore> list = lifeCycleMineStoreService.list(
                    new LambdaQueryWrapper<LifeCycleMineStore>()
                            .eq(LifeCycleMineStore::getRegClassCode, savePedigeePO.getRegClassCode())
                            .eq(LifeCycleMineStore::getYear, savePedigeePO.getYear())
                            .eq(LifeCycleMineStore::getMineralCode, savePedigeePO.getMineralCode())
            );*/
//            if(CollUtil.isNotEmpty(list)){
//            LifeCycleMineStore lifeCycleMineStore = CollUtil.getFirst(list);
//            保存矿石类型储量值
//            result = saveCycleLifeMineralMea(lifeCycleMineStore);
                LifeCycleMineStore lifeCycleMineStore = new LifeCycleMineStore();
                lifeCycleMineStore.setContinueDate(savePedigeePO.getContinueDate());
                lifeCycleMineStore.setApproveStatus(savePedigeePO.getApproveStatus());
                saveLifeCycleDataSingle(zlxqcx,lifeCycleMineStore);

                LifeCyclePedigee lifeCyclePedigee = new LifeCyclePedigee();
                lifeCyclePedigee.setMineStoreId(lifeCycleMineStore.getId());

                if(checkIsFirstPedigeeNode(savePedigeePO.getRegClassCode(), savePedigeePO.getMineralCode())){
//                lifeCyclePedigee.setId(savePedigeePO.getMineralCode()+"_"+lifeCycleService.getRegClassCodeSuffixTwo(savePedigeePO.getRegClassCode()));
                    lifeCyclePedigee.setId(savePedigeePO.getParentId()+"_"+savePedigeePO.getYear());
                    lifeCyclePedigee.setParentId("0");
                }else{
                    String parentId = getNewestPedigeeParentId(lifeCycleMineStore);
                    lifeCyclePedigee.setId(savePedigeePO.getId()+"_"+savePedigeePO.getYear());
                    lifeCyclePedigee.setParentId(parentId);
//                    lifeCyclePedigee.setParentId(savePedigeePO.getParentId()+"_"+savePedigeePO.getYear());
                }
//                result = lifeCyclePedigeeService.save(lifeCyclePedigee);

//            }

        }else{
            log.warn("许可证号:"+savePedigeePO.getId()+"年度："+savePedigeePO.getYear()+"匹配不到矿山数据");
        }

        return result;
    }


    /**
     * 得到左心的图谱id
     * @return
     */
    private String getNewestPedigeeParentId(LifeCycleMineStore lifeCycleMineStore){
        String result = null;
        List<LifeCyclePedigee> pedigees = lifeCycleMineStoreMapper.selectJoinList(LifeCyclePedigee.class,new MPJLambdaWrapper<LifeCycleMineStore>()
                .selectAll(LifeCyclePedigee.class)
                .leftJoin(LifeCyclePedigee.class,LifeCyclePedigee::getMineStoreId, LifeCycleMineStore::getId)
                .eq(LifeCycleMineStore::getRegClassCode, lifeCycleMineStore.getRegClassCode())
                .eq(LifeCycleMineStore::getMineralCode, lifeCycleMineStore.getMineralCode())
                .isNotNull(LifeCyclePedigee::getId)
//                .eq(LifeCycleMineStore::getYear, lifeCycleMineStore.getYear())
                .orderByDesc(LifeCycleMineStore::getStoreDate)
        );
        if(CollUtil.isNotEmpty(pedigees)){
            result = CollUtil.getFirst(pedigees).getId();
        }

        return result;
    }

    /**
     * 检查是否是第一个节点族谱
     * @param regClassCode 登记分类编号
     * @param mineralCode 矿区编号
     * @return
     */
    private boolean checkIsFirstPedigeeNode(Integer regClassCode, String mineralCode){
        boolean result = true;
        List<QueryMineStoreVO> queryMineStoreVOS = lifeCycleMineStoreMapper.selectJoinList(QueryMineStoreVO.class
                ,new MPJLambdaWrapper<LifeCycleMineStore>()
                .selectCollection(LifeCyclePedigee.class, QueryMineStoreVO::getLifeCyclePedigeeList)
                .leftJoin(LifeCyclePedigee.class, LifeCyclePedigee::getMineStoreId, LifeCycleMineStore::getId)
                .eq(LifeCycleMineStore::getMineralCode, mineralCode)
                .apply(lifeCycleService.getQueryLifeCycleApplySQL("t",regClassCode))
        );

        for (QueryMineStoreVO queryMineStoreVO:queryMineStoreVOS) {
            if(CollUtil.isNotEmpty(queryMineStoreVO.getLifeCyclePedigeeList())){
                result = false;
                break;
            }
        }

        return result;
    }

    /**
     * 生命周期节点id
     * @param lifeCycleMineStore 生命周期节点实体
     * @return
     */
    @Override
    public boolean saveCycleLifeMineralMea(LifeCycleMineStore lifeCycleMineStore){
        boolean result = true;
        QueryYearStorePO queryYearStorePO = new QueryYearStorePO();
        queryYearStorePO.setYear(lifeCycleMineStore.getYear());
        queryYearStorePO.setZycllb(19001);
        queryYearStorePO.setMineralCode(lifeCycleMineStore.getMineralCode());
        queryYearStorePO.setRegClassCode(lifeCycleMineStore.getRegClassCode());
        List<QuerYearStoreVO> querYearStoreVOS = lifeCycleMapper.staticsMineralStorerVal(queryYearStorePO);
        if(CollUtil.isNotEmpty(querYearStoreVOS)){
            List<LifeCycleMineralMea> lifeCycleMineralMeas = CollUtil.newArrayList();
            for (QuerYearStoreVO querYearStoreVO :querYearStoreVOS) {
                LifeCycleMineralMea lifeCycleMineralMea = new LifeCycleMineralMea();
                lifeCycleMineralMea.setMineStoreId(lifeCycleMineStore.getId());
                lifeCycleMineralMea.setMineralType(querYearStoreVO.getKcdm());
                lifeCycleMineralMea.setStoreVal(querYearStoreVO.getStoreVal());
                lifeCycleMineralMea.setTjdx(querYearStoreVO.getTjdx());
                lifeCycleMineralMea.setSaveTime(Convert.toLocalDateTime(DateUtil.now()));
                lifeCycleMineralMea.setTypeStand(3);
                List<KclCb06Kc> kclCb06Kcs = kclCb06KcMapper.selectList(new LambdaQueryWrapper<KclCb06Kc>().eq(KclCb06Kc::getKcdm,querYearStoreVO.getKcdm()).eq(KclCb06Kc::getTjdx,querYearStoreVO.getTjdx()));
                if(CollUtil.size(kclCb06Kcs)!=0){
                    KclCb06Kc kclCb06Kc = CollUtil.getFirst(kclCb06Kcs);
                    lifeCycleMineralMea.setKclb(kclCb06Kc.getKclb());
                }

                lifeCycleMineralMeas.add(lifeCycleMineralMea);
            }
            result = lifeCycleMineralMeaService.saveBatch(lifeCycleMineralMeas,20);
        }else{
            List<KclZycl> kclZycls = kclZyclMapper.selectList(new LambdaQueryWrapper<KclZycl>()
                    .eq(KclZycl::getDjflbh, lifeCycleMineStore.getRegClassCode())
                    .eq(KclZycl::getKqbh, String.valueOf(lifeCycleMineStore.getRegClassCode() ))
                    .eq(KclZycl::getZycllb,19001)
                    .eq(KclZycl::getNd, lifeCycleMineStore.getYear())
            );
            List<String> kcs = kclZycls.stream().map(ele->ele.getKcdm()+"_"+(ObjectUtil.isNotEmpty(ele.getTjdx())?ele.getTjdx():0)).distinct().collect(Collectors.toList());
            for (String kc:kcs) {
                List<String> kcSp = StrUtil.split(kc,"_");
                Integer kcdm = Convert.toInt(CollUtil.getFirst(kcSp));
                Integer tjdx = Convert.toInt(CollUtil.getLast(kcSp));
                LifeCycleMineralMea lifeCycleMineralMea = new LifeCycleMineralMea();
                lifeCycleMineralMea.setMineStoreId(lifeCycleMineStore.getId());
                lifeCycleMineralMea.setMineralType(kcdm);
                lifeCycleMineralMea.setTjdx(tjdx);
                lifeCycleMineralMea.setTypeStand(3);
                lifeCycleMineralMea.setStoreVal(null);
                lifeCycleMineralMea.setSaveTime(Convert.toLocalDateTime(DateUtil.now()));
                List<KclCb06Kc> kclCb06Kcs = kclCb06KcMapper.selectList(new LambdaQueryWrapper<KclCb06Kc>().eq(KclCb06Kc::getKcdm,kcdm).eq(KclCb06Kc::getTjdx,tjdx));
                if(CollUtil.size(kclCb06Kcs)!=0){
                    KclCb06Kc kclCb06Kc = CollUtil.getFirst(kclCb06Kcs);
                    lifeCycleMineralMea.setKclb(kclCb06Kc.getKclb());
                }

                lifeCycleMineralMeaService.save(lifeCycleMineralMea);
            }

//            lifeCycleMineralMeas.add(lifeCycleMineralMea);
        }
        return result;
    }

    /**
     * 获取生命周期实体
     * @param zlxqcx 资料信息实体
     * @return
     */
    private LifeCycleMineStore getMineStoreByZlxqcx(Zlxqcx zlxqcx,LifeCycleMineStore result){
//        LifeCycleMineStore result = new LifeCycleMineStore();
        result.setFileId(zlxqcx.getGuanlianId());
        result.setMineralAreaPath(getAreaImgPath(zlxqcx.getKyqklx()));
//        资料日期
        result.setStoreDate(Convert.convert(LocalDate.class,zlxqcx.getZlsj()));
//        探矿权类型
        result.setExporeType(zlxqcx.getKyqklx());
//        等级分类编号
        result.setRegClassCode(zlxqcx.getDjflbh());
        KclCb01Zh kclCb01Zh = kclCb01ZhMapper.selectOne(new LambdaQueryWrapper<KclCb01Zh>().eq(KclCb01Zh::getDm,zlxqcx.getZlxz()));
        if(ObjUtil.isNotEmpty(kclCb01Zh)){
            result.setReportName(kclCb01Zh.getMc());
        }
        result.setYear(zlxqcx.getNd());
        result.setMineralCode(zlxqcx.getKqbh());
        result.setSaveTime(Convert.toLocalDateTime(DateUtil.now()));

        List<KclZb> kclZbs = queryCoor(zlxqcx);
//        List<ZyclVO> zyclVOS = queryMineStoreData(zlxqcx);
        if(CollUtil.isNotEmpty(kclZbs)){

            KclZb kclZb = CollUtil.getFirst(kclZbs);
//            result.setStoreVal(zyclVO.getStoreVal());
            result.setDmlCoor(kclZb.getKqzb());
            result.setCalCoor(kclZb.getJszb());
            result.setMomCoor(kclZb.getDlzb());
        }

        return result;
    }

    private String getAreaImgPath(Integer exportType){
        String result = null;
        if(StrUtil.equals(CollUtil.get(LifeCycleConstant.mineTypeCodes,0),Convert.toStr(exportType))){
            result = "/src/assets/reserves/无矿权.png";
        }else if(StrUtil.equals(CollUtil.get(LifeCycleConstant.mineTypeCodes,1),Convert.toStr(exportType))){
            result = "/src/assets/reserves/探矿权.png";
        }else if(StrUtil.equals(CollUtil.get(LifeCycleConstant.mineTypeCodes,2),Convert.toStr(exportType))){
            result = "/src/assets/reserves/采矿权.png";
        }

        return result;

    }

    /**
     * 得到储量值
     * @param zlxqcx
     * @return
     */
    private List<KclZb> queryCoor(Zlxqcx zlxqcx){
//        String result = "0";
        /*MPJLambdaWrapper wrapper = new MPJLambdaWrapper<KclZycl>()
                .selectFunc(FuncEnum.CASE_STORE_VAL.getSql(),arg->arg.accept(KclCb06Kc::getJsldw, KclZycl::getKsl,KclZycl::getJsl),ZyclVO::getStoreVal)
                .selectAs(KclZb::getKqzb, ZyclVO::getDmlCoor)
                .selectAs(KclZb::getJszb, ZyclVO::getCalCoor)
                .leftJoin(KclCb06Kc.class, KclCb06Kc::getKcdm, KclZycl::getKcdm)
                .leftJoin(KclZb.class,on->
                        on.eq(KclZb::getDjflbh,KclZycl::getDjflbh)
                                .eq(KclZb::getNd, KclZycl::getNd)
                                .eq(KclZb::getKqbh, KclZycl::getKqbh))

                .eq(KclZycl::getDjflbh, zlxqcx.getDjflbh())
                .eq(KclZycl::getNd, zlxqcx.getNd())
                .eq(KclZycl::getKqbh, zlxqcx.getKqbh());*/



//          List<ZyclVO> zyclVOS = kclZyclMapper.selectJoinList(ZyclVO.class,wrapper);
          /*if(CollUtil.isNotEmpty(zyclVOS)){

              ZyclVO zyclVO = CollUtil.getFirst(zyclVOS);
              lifeCycleMineStore.setStoreVal(zyclVO.getStoreVal());
              lifeCycleMineStore.setDmlCoor(zyclVO.getDmlCoor());
              lifeCycleMineStore.setCalCoor(zyclVO.getCalCoor());
          }*/
        LambdaQueryWrapper wrapper =new LambdaQueryWrapper<KclZb>().eq(KclZb::getDjflbh, zlxqcx.getDjflbh())
                .eq(KclZb::getNd, zlxqcx.getNd())
                .eq(KclZb::getKqbh, zlxqcx.getKqbh());
          return kclZbMapper.selectList(wrapper);
    }

    /**
     * 得到生命周期节，并初始化族谱列表
     * @return
     */
    private LifeCyclePedigee getLcNodePed(LifeCyclePedigee lifeCyclePedigee
            ,AdJoinPedNodeVO adJoinPedNodeVO
            ,SaveLCNodePO saveLCNodePO
    ){
            //            得到当前矿区所有的族谱节点
            lifeCyclePedigee.setMineStoreId(saveLCNodePO.getId());
            LifeCyclePedigeeNodeVO preLcPed = adJoinPedNodeVO.getPrePedNode();
//            如果存在前一个节点,并且上一个节点名字不是压覆报告的
            if(ObjectUtil.isNotEmpty(adJoinPedNodeVO.getPrePedNode()) && !StrUtil.equals(preLcPed.getNodeName(), CollUtil.getFirst(LifeCycleConstant.crePedNodTypes))){
                if(StrUtil.isBlank(lifeCyclePedigee.getParentId())){
                    lifeCyclePedigee.setParentId(adJoinPedNodeVO.getPrePedNode().getPedId());
                }

//                saveLCNodePO.setPreStoreDate(adJoinPedNodeVO.getPrePedNode().getNodeDate());
            }

//            saveLCNodePO.setLifeCyclePedigeeList(CollUtil.newArrayList(lifeCyclePedigee));
//            如果存在后一个节点
            /*if(ObjectUtil.isNotEmpty(adJoinPedNodeVO.getNextPedNode())){
                saveLCNodePO.setNextPedigeeVals(CollUtil.newArrayList(adJoinPedNodeVO.getNextPedNode().getPedId()));
            }*/
        return lifeCyclePedigee;
    }

    private List<LifeCyclePedigee> getPeds(SaveLCNodePO saveLCNodePO,AdJoinPedNodeVO adJoinPedNodeVO){
        List<LifeCyclePedigee> result =CollUtil.newArrayList();
//        如果是压覆
        if(StrUtil.equals(CollUtil.getFirst(LifeCycleConstant.crePedNodTypes),saveLCNodePO.getReportName())){
            saveLCNodePO.init();
            if(!StrUtil.startWith(Convert.toStr(saveLCNodePO.getRegClassCode()),"4")){
                for (int i = 1; i < 3; i++) {
                    String curPedId = lifeCycleDataManagerService.getPedId(
                            saveLCNodePO.getMineralCode()
                            ,saveLCNodePO.getRegClassCode()
                            ,saveLCNodePO.getStoreDate(),
                            i
                    );
                    LifeCyclePedigee lifeCyclePedigee = BeanUtil.copyProperties(saveLCNodePO, LifeCyclePedigee.class);
                    lifeCyclePedigee.setId(curPedId);
                    if(StrUtil.isNotBlank(saveLCNodePO.getParentId())){
                        lifeCyclePedigee.setParentId(saveLCNodePO.getParentId());
                    }
                    if(i==2){
                        if(ObjectUtil.isNotEmpty(adJoinPedNodeVO.getPrePedNode())){
                            lifeCyclePedigee.setName(LifeCycleConstant.kqxbg);
//                            设置上一个节点的名车给
//                            lifeCyclePedigee.setName(adJoinPedNodeVO.getPrePedNode().getNodeName());
                            lifeCyclePedigee.setExporeType(adJoinPedNodeVO.getPrePedNode().getExporeType());
                        }
                    }else{
                        lifeCyclePedigee.setName(saveLCNodePO.getReportName());
                        lifeCyclePedigee.setExporeType(Convert.toInt(LifeCycleConstant.mineTypeCodes.get(0)));
                    }
                    result.add(lifeCyclePedigee);

                }
            }

        }else{
            saveLCNodePO.init();
//            如果不是分立的
            if(!saveLCNodePO.getIsDiscrete()){
                String curPedId = lifeCycleDataManagerService.getPedId(
                        saveLCNodePO.getMineralCode()
                        ,saveLCNodePO.getRegClassCode()
                        ,saveLCNodePO.getStoreDate(),
                        null
                );
                LifeCyclePedigee lifeCyclePedigee = BeanUtil.copyProperties(saveLCNodePO, LifeCyclePedigee.class);
                lifeCyclePedigee.setId(curPedId);
                lifeCyclePedigee.setName(saveLCNodePO.getReportName());
                if(StrUtil.isNotBlank(saveLCNodePO.getParentId())){
                    lifeCyclePedigee.setParentId(saveLCNodePO.getParentId());
                }
                result.add(lifeCyclePedigee);
            }else{
                /*是分立*/
                /*判断是否是编辑*/
                /*是编辑*/
                LifeCycleMineStore flNode = getFLLCNode(saveLCNodePO);

                if(ObjectUtil.isEmpty(flNode)){
                    result.add(getFLPed(saveLCNodePO,1));
                }else{
                    saveLCNodePO.setId(flNode.getId());
                    /*对索引进行排序*/
                    Integer maxInd = 0;
                    if(ObjectUtil.isNotEmpty(saveLCNodePO.getXlIndex())){
                        maxInd = saveLCNodePO.getXlIndex()-1;
                    }else{
                        //                    查询数据库中已经存在的分立族谱
                        List<LifeCyclePedigee> flLcps = lifeCyclePedigeeService.lambdaQuery().eq(LifeCyclePedigee::getMineStoreId,saveLCNodePO.getId()).list();
                        /*分立索引类列表*/
                        List<String> inds = CollUtil.newArrayList();
                        for (LifeCyclePedigee ele:flLcps) {
                            String pedId = ele.getId();
                            /*如果登记分类编号大于4，则说明在登记分类编号后面加上了分立索引*/
                            String djflbh = CollUtil.get(StrUtil.split(pedId,"_"),1);
                            if(StrUtil.length(djflbh)>4){
                                inds.add(StrUtil.sub(djflbh, 4,StrUtil.length(djflbh)));
                            }
                        }

                        if(CollUtil.size(inds)>0){
                            inds = CollUtil.sort(inds, new Comparator<String>() {
                                @Override
                                public int compare(String o1, String o2) {
                                    return Convert.toInt(o1)-Convert.toInt(o2);
                                }
                            });

                            maxInd = Convert.toInt(CollUtil.getLast(inds));
                        }
                    }

                    result.add(getFLPed(saveLCNodePO,maxInd+1));
                }

                /*if(ObjectUtil.isNotEmpty(saveLCNodePO.getDiscreteNum())){
                    for (int i = 1; i < saveLCNodePO.getDiscreteNum()+1; i++) {

                        result.add(getFLPed(saveLCNodePO,i));

                    }
                }*/


                /*if(ObjectUtil.isNotEmpty(saveLCNodePO.getDiscreteNum())){
                    for (int i = 1; i < saveLCNodePO.getDiscreteNum()+1; i++) {
                        LifeCyclePedigee lifeCyclePedigee = BeanUtil.copyProperties(saveLCNodePO, LifeCyclePedigee.class);
                        String curPedId = lifeCycleDataManagerService.getPedId(
                                saveLCNodePO.getMineralCode()
                                ,saveLCNodePO.getRegClassCode()
                                ,saveLCNodePO.getStoreDate(),
                                i
                        );
                        lifeCyclePedigee.setId(curPedId);
                        if(StrUtil.isNotBlank(saveLCNodePO.getParentId())){
                            lifeCyclePedigee.setParentId(saveLCNodePO.getParentId());
                        }
                        lifeCyclePedigee.setXlIndex(i);
                        lifeCyclePedigee.setName(saveLCNodePO.getReportName());
                        result.add(lifeCyclePedigee);

                    }
                }*/

            }

        }
        return result;
    }

    /**
     * 得到分立生命周期节点
     * @param saveLCNodePO 保存节点的po类
     * @return
     */

    public LifeCycleMineStore getFLLCNode(SaveLCNodePO saveLCNodePO){
        LifeCycleMineStore result = null;
        List<LifeCycleMineStore> lcms = lifeCycleMineStoreService.lambdaQuery()
                .eq(LifeCycleMineStore::getRegClassCode,saveLCNodePO.getRegClassCode())
                .eq(LifeCycleMineStore::getStoreDate,saveLCNodePO.getStoreDate())
                .eq(LifeCycleMineStore::getMineralCode,saveLCNodePO.getMineralCode())
//                .eq(LifeCycleMineStore::getReportName,saveLCNodePO.getReportName())
                .list();

        if(CollUtil.isNotEmpty(lcms)){
            result = CollUtil.getFirst(lcms);
        }
        return result;
    }

    /**
     * 得到分立族谱
     * @param saveLCNodePO 保存节点PO类
     * @param i 分立索引
     * @return
     */
    private LifeCyclePedigee getFLPed(SaveLCNodePO saveLCNodePO,Integer i){
        LifeCyclePedigee lifeCyclePedigee = BeanUtil.copyProperties(saveLCNodePO, LifeCyclePedigee.class);
        String curPedId = lifeCycleDataManagerService.getPedId(
                saveLCNodePO.getMineralCode()
                ,saveLCNodePO.getRegClassCode()
                ,saveLCNodePO.getStoreDate(),
                i
        );
        lifeCyclePedigee.setId(curPedId);
        if(StrUtil.isNotBlank(saveLCNodePO.getParentId())){
            lifeCyclePedigee.setParentId(saveLCNodePO.getParentId());
        }
        lifeCyclePedigee.setXlIndex(i);
        lifeCyclePedigee.setName(saveLCNodePO.getReportName());

        return lifeCyclePedigee;
    }

    /**
     * 验证是否是分立
     * @return
     */
    private boolean validIsFL(SaveLCNodePO saveLCNodePO){
        boolean result = false;
        /*如果类型符合条件*/
        if(CollUtil.contains(LifeCycleConstant.flPedTypes,saveLCNodePO.getReportName())){
            result = true;
        }
        return result;
    }
    /**
     * 初始化族谱列表
     */
    @Override
    public void initPedList(SaveLCNodePO saveLCNodePO){
//        在允许生成族谱节点的列表中
        if(CollUtil.contains(LifeCycleConstant.crePedNodTypes,saveLCNodePO.getReportName())){

            List<LifeCyclePedigeeNodeVO> lifeCyclePedigeeNodeVOS = lifeCycleDataManagerService.queryPedigeeLifeCycleNodes(saveLCNodePO.getMineralCode(),lifeCycleService.getQueLcRegClassCodes(saveLCNodePO.getRegClassCode()));

            AdJoinPedNodeVO adJoinPedNodeVO = new AdJoinPedNodeVO();
//            初始化前一个节点和后一个节点
            adJoinPedNodeVO.initAdJoin(lifeCyclePedigeeNodeVOS,saveLCNodePO.getStoreDate(),saveLCNodePO.getIsDiscrete());

//            得到当前族谱id
            List<LifeCyclePedigee> lcps = getPeds(saveLCNodePO,adJoinPedNodeVO);
            List<LifeCyclePedigee> peds = CollUtil.newArrayList();
            for (int i = 0; i < CollUtil.size(lcps); i++) {
                LifeCyclePedigee lifeCyclePedigee = CollUtil.get(lcps,i);
                peds.add(getLcNodePed(lifeCyclePedigee,adJoinPedNodeVO,saveLCNodePO));
            }

            saveLCNodePO.setLifeCyclePedigeeList(peds);

            if(ObjectUtil.isNotEmpty(adJoinPedNodeVO.getPrePedNode()) && ObjectUtil.isEmpty(saveLCNodePO.getPreStoreDate())){
                saveLCNodePO.setPreStoreDate(adJoinPedNodeVO.getPrePedNode().getNodeDate());
            }
//            如果存在后一个节点
            if(ObjectUtil.isNotEmpty(adJoinPedNodeVO.getNextPedNode()) && CollUtil.isEmpty(saveLCNodePO.getNextPedigeeVals())){
                saveLCNodePO.setNextPedigeeVals(CollUtil.newArrayList(adJoinPedNodeVO.getNextPedNode().getPedId()));
            }

        }

    }



    @Override
    @Transactional
    public WebResult saveLcNode(PAFPushPO pafPushPO) {
        Console.log("传过来的", JSONUtil.toJsonStr(pafPushPO));
//        检查节点时间是否存在
        CheckNodeDatePO checkNodeDatePO = BeanUtil.copyProperties(pafPushPO,CheckNodeDatePO.class);
        boolean isExt = lifeCycleDataManagerService.checkNodeDateExist(checkNodeDatePO);
        if(!isExt){
            boolean isSuccess = true;
            SaveLCNodePO saveLCNodePO = BeanUtil.copyProperties(pafPushPO,SaveLCNodePO.class);
//            初始化族谱列表(包括前一个节点,和后一个节点)
            initPedList(saveLCNodePO);

            isSuccess=lifeCycleDataManagerService.saveOrUpdateLCNode(saveLCNodePO);
//            插入储量
            List<LifeCycleMineralMea> lifeCycleMineralMeas =  pafPushPO.getLifeCycleMineralMeas();
            if(CollUtil.size(lifeCycleMineralMeas)!=0){
                lifeCycleMineralMeas = lifeCycleMineralMeas.stream().map(ele->{
                    ele.setMineStoreId(saveLCNodePO.getId());
                    return ele;
                }).collect(Collectors.toList());

                isSuccess = lifeCycleMineralMeaService.saveBatch(lifeCycleMineralMeas,5);
            }
            if(isSuccess){
                return new WebResult(WebResultStatusConstant.SUCCESS_OPERATION.getCode(), WebResultStatusConstant.SUCCESS_OPERATION.getMsg());
            }else{
                return new WebResult(WebResultStatusConstant.FAILE.getCode(), WebResultStatusConstant.FAILE.getMsg());
            }

        }else{
            return new WebResult(WebResultStatusConstant.CUSTOM.getCode(), "日期已存在");
        }

    }
}

